﻿using Super.Admin.Global;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Views.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Super.Admin.Utils
{
    public class LanguageHelper
    {
        public static readonly Lazy<LanguageHelper> _instance = new Lazy<LanguageHelper>(() => new LanguageHelper());
        public static LanguageHelper Instance => _instance.Value;
        private LanguageHelper() { }
        private static Dictionary<LanguageType, Langs> _resources = new Dictionary<LanguageType, Langs>();

        /// <summary>
        /// 初始化语言资源
        /// </summary>
        public void Initialize()
        {
            LoadLanguage(LanguageType.English, $"{FilePath.LanguagesFilePath}Language.en-US.xml");
            LoadLanguage(LanguageType.Chinese, $"{FilePath.LanguagesFilePath}Language.zh-CN.xml");
            LoadLanguage(LanguageType.Japanese, $"{FilePath.LanguagesFilePath}Language.ja-JP.xml");
        }

        /// <summary>
        /// 加载语言文件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="filePath"></param>
        public void LoadLanguage(LanguageType type, string filePath)
        {
            if (!File.Exists(filePath)) return;
            try
            {
                var serializer = new XmlSerializer(typeof(Langs));
                using (var stream = new FileStream(filePath, FileMode.Open))
                {
                    _resources[type] = (Langs)serializer.Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载语言文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置当前语言
        /// </summary>
        /// <param name="type"></param>
        public void SwitchLanguage()
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form is Views.Base.BaseForm baseForm)
                {
                    baseForm.RefreshLanguage(form);
                }
            }
        }


        /// <summary>
        /// 获取当前语言对应的字符串资源
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetString(string key)
        {
            if (_resources.TryGetValue(ThemeSettingHelper.Instance.ThemeConfig.GeneralSettings.General.Language, out Langs langs))
            {
                var item = langs.Items.Where(i => i.Name == key).FirstOrDefault();
                if(item != null && !string.IsNullOrEmpty(item.Value))
                {
                    return item.Value;
                }
            }
            return null;
        }
    }
}
